import 'dart:convert';

import 'package:example_example/pages/view/LoadingDialog.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../global/Global.dart';
import '../global/GlobalUrl.dart';
import '../services/TLSizeFit.dart';

import 'package:webview_flutter/webview_flutter.dart';

import '../YColors.dart';
import 'LogUtil.dart';
import 'Storage.dart';
import 'check.dart';

/**
 * https://www.jianshu.com/p/4aabe453eb26
 * https://pub.dev/packages/webview_flutter/example
 */
class WebViewUtilPage extends StatefulWidget {
  Map arguments;

  WebViewUtilPage({Key key, this.arguments}) : super(key: key);

  @override
  _WebViewPageState createState() => _WebViewPageState();
}

class _WebViewPageState extends State<WebViewUtilPage> {
  WebViewController _controller;
  String _title = "";
  String url = "";
  String WEBVIEW_TAG = "";
  String getId = "";
  String dataStr = "";
  String variableJsonStr = "";
  int count = 0;
  var bean;

//  String filePath = 'assets/files/aboutus.html';
  String filePath = 'files/aboutus.html';
  bool flagLoading = true ;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    _title = widget.arguments["title"];
    url = widget.arguments["url"];
//    url = Uri.encodeComponent(url);
//    print("工具类获取的111url:$url");
//    url = Uri.decodeComponent(url);


    WEBVIEW_TAG = widget.arguments[Global.WEBVIEW_TAG];
    getId = widget.arguments["id"];
    count = widget.arguments["count"];
    variableJsonStr = widget.arguments["variableJsonStr"];
    print("工具类获取的222url:$url");



//    dataStr =  widget.arguments["dataStr"];

//    String dataStr = json.encode(widget.arguments["dataStr"]); // 转为字符串
//    bean = json.decode(dataStr);

//    print("获取的数据dataStr：$dataStr");
//    print("bean：$bean");

    if (PicketUtil.strEmpty(_title)) {
      _title = "";
    }

    if (PicketUtil.strEmpty(url)) {
      url = "";
    }
    if (PicketUtil.strEmpty(getId)) {
      getId = "";
    }
    _setWebviewUrl();

//    url = "http://192.168.20.114:8181/test/test.html";

    LogUtil.init(title: "来自LogUtil", isDebug: false, limitLength: 800);
    LogUtil.v("获取的url:$url");
  }

  String _setWebviewUrl() {
//    String url = "";
    switch (WEBVIEW_TAG) {
      case Global.HELP:
        url = GlobalUrl.HELP;
        _title = "帮助";
        break;

      case Global.HIISTORYTASK:
//        url = GlobalUrl.HISTORYURL+"?processInstanceId="+getId;
//          url = "http://192.168.20.114:8181/#/app/index";
//          url = "http://192.168.20.114:8181/test/test.html";
//          url = "http://127.0.0.1:5500";
//          url = "http://10.66.1.50:5500";  // 更换为自己IP地址
//          url = "http://10.66.1.50:5501";  // 更换为自己IP地址

//        String id = bean["id"];
//        String utcRoutePath = bean["utcRoutePath"];
//        String utcInterfaceUrl = bean["utcInterfaceUrl"];
//        String utcType = bean.utcType;
//        String utcTitle = bean.utcTitle;
//        String utcFormId = bean.utcFormId;
//        String utcFormType = bean.utcFormType;
//        String taskDefinitionKey = bean.taskDefinitionKey;
//        String variableJson = bean.variableJson;
//        String processInstanceId = bean.processInstanceId;
//
//        print("id:$id");
//        print("utcRoutePath:$utcRoutePath");
//        print("utcInterfaceUrl:$utcInterfaceUrl");
//        print("utcType:$utcType");
//        print("utcTitle:$utcTitle");
//        print("taskDefinitionKey:$taskDefinitionKey");

//          url = "http://192.168.20.114:8181/test/test.html?id=3e383f7b-1cfd-11ec-84d3-8677265336d4&utcRoutePath=supplier%2Fenterprise%2Fapprove&utcInterfaceUrl=%2Fus-upms%2Fsupplier%2FcompanyInfo%2FupdateAndSubmitAudit&utcType=2&utcTitle=%E4%BE%9B%E5%BA%94%E5%95%86%E4%BF%A1%E6%81%AF%E4%BF%AE%E6%94%B9&name=%E4%BE%9B%E5%BA%94%E5%95%86%E4%BF%A1%E6%81%AF%E4%BF%AE%E6%94%B9&utcFormId=1404671449536442369&utcFormType=1&taskDefinitionKey=UT_SB_COMPANY_INFO_EDIT&variableJson=%7B%22eiLegalPersonType%22%3Anull,%22eiEndTime%22%3Anull,%22eiAlias%22%3A%22%E8%B5%9B%E5%A2%A8%22,%22eiHistoryNames%22%3Anull,%22initiator%22%3A%223%22,%22eiUnifiedSocialCreditCode%22%3A%2291310117057659519U%22,%22ciGoodsType%22%3A%223%22,%22eiName%22%3A%22%E8%B5%9B%E5%A2%A8%EF%BC%88%E4%B8%8A%E6%B5%B7%EF%BC%89%E4%BF%A1%E6%81%AF%E6%8A%80%E6%9C%AF%E6%9C%89%E9%99%90%E5%85%AC%E5%8F%B8%22,%22title%22%3A%22%E8%B5%9B%E5%A2%A8%EF%BC%88%E4%B8%8A%E6%B5%B7%EF%BC%89%E4%BF%A1%E6%81%AF%E6%8A%80%E6%9C%AF%E6%9C%89%E9%99%90%E5%85%AC%E5%8F%B8%22,%22ciStatus%22%3A%221101%22,%22approvalRemark%22%3A%221%22,%22peopleInfoEditVos%22%3A%5B%7B%22id%22%3A%221441279472851345409%22,%22ubRealname%22%3A%22%E6%9D%8E%E5%9B%9B%22,%22ubPhone%22%3A%2213209087654%22,%22piRealname%22%3A%22%E6%9D%8E%E5%9B%9B%22,%22piPhone%22%3A%2213209087654%22,%22piEmail%22%3Anull,%22piCertificateType%22%3Anull,%22piCertificateNumber%22%3Anull,%22sbCompanyInfoId%22%3A%221441279471412699137%22,%22piDepartment%22%3A%22%22,%22piPosition%22%3A%22%22,%22piBelongSalesId%22%3Anull,%22piBelongSalesName%22%3Anull,%22piType%22%3A%221%22,%22piRegisterSource%22%3A%2211%22,%22validFlag%22%3A%221%22,%22validFlagStr%22%3A%22%E6%9C%89%E6%95%88%22%7D%5D,%22eiRegStatus%22%3A%22%E5%AD%98%E7%BB%AD%22,%22updateUserTenantId%22%3A1,%22eiLegalPersonName%22%3A%22%E5%80%AA%E5%AE%87%E5%B3%B0%22,%22eiTaxNumber%22%3A%2291310117057659519U%22,%22eiIndustry%22%3A%22%E7%A7%91%E6%8A%80%E6%8E%A8%E5%B9%BF%E5%92%8C%E5%BA%94%E7%94%A8%E6%9C%8D%E5%8A%A1%E4%B8%9A%22,%22id%22%3A%221441279471412699137%22,%22eiRegCapital%22%3A%22500%E4%B8%87%E4%BA%BA%E6%B0%91%E5%B8%81%22,%22eiRegLocation%22%3A%22%E4%B8%8A%E6%B5%B7%E5%B8%82%E6%9D%BE%E6%B1%9F%E5%8C%BA%E7%9F%B3%E6%B9%96%E8%8D%A1%E9%95%87%E9%95%BF%E5%A1%94%E8%B7%AF1000%E5%BC%842%E5%8F%B7104%E5%AE%A4%22,%22approvalStatus%22%3A%222%22,%22eiBondNum%22%3Anull,%22eiStaffNumRange%22%3A%22-%22,%22userTaskId%22%3Anull,%22ciGoodsTypeList%22%3A%5B%223%22%5D,%22updateUserId%22%3A1436890466776903681,%22ciGoodsBrand%22%3A%22%22,%22updateUserName%22%3A%22%E8%B5%B5%E7%94%9C%E7%94%9C%22,%22ciCompanyApprovalProcessId%22%3Anull,%22eiUsedBondName%22%3Anull,%22updateTime%22%3A%222021-09-24%2006%3A04%3A13%22,%22updateUserOrganizationId%22%3A1430356768858243074,%22eiFromTime%22%3Anull,%22eiEnterpriseOrgType%22%3A%22%E6%9C%89%E9%99%90%E8%B4%A3%E4%BB%BB%E5%85%AC%E5%8F%B8%28%E8%87%AA%E7%84%B6%E4%BA%BA%E6%8A%95%E8%B5%84%E6%88%96%E6%8E%A7%E8%82%A1%29%22,%22ciRemark%22%3Anull,%22ciCompanyType%22%3A%221%22,%22eiBondName%22%3Anull,%22eiBusinessScope%22%3A%22%E4%BF%A1%E6%81%AF%E6%8A%80%E6%9C%AF%E3%80%81%E8%AE%A1%E7%AE%97%E6%9C%BA%E8%BD%AF%E4%BB%B6%EF%BC%88%E9%99%A4%E8%AE%A1%E7%AE%97%E6%9C%BA%E4%BF%A1%E6%81%AF%E7%B3%BB%E7%BB%9F%E5%AE%89%E5%85%A8%E4%B8%93%E7%94%A8%E4%BA%A7%E5%93%81%EF%BC%89%E3%80%81%E7%BD%91%E7%BB%9C%E7%A7%91%E6%8A%80%E3%80%81%E4%BF%A1%E6%81%AF%E7%B3%BB%E7%BB%9F%E9%A2%86%E5%9F%9F%E5%86%85%E6%8A%80%E6%9C%AF%E6%9C%8D%E5%8A%A1%E3%80%81%E6%8A%80%E6%9C%AF%E5%BC%80%E5%8F%91%E3%80%81%E6%8A%80%E6%9C%AF%E5%92%A8%E8%AF%A2%E3%80%81%E6%8A%80%E6%9C%AF%E8%BD%AC%E8%AE%A9%EF%BC%8C%E4%BC%81%E4%B8%9A%E7%AE%A1%E7%90%86%E5%92%A8%E8%AF%A2%EF%BC%8C%E8%AE%A1%E7%AE%97%E6%9C%BA%E8%BD%AF%E7%A1%AC%E4%BB%B6%EF%BC%88%E9%99%A4%E8%AE%A1%E7%AE%97%E6%9C%BA%E4%BF%A1%E6%81%AF%E7%B3%BB%E7%BB%9F%E5%AE%89%E5%85%A8%E4%B8%93%E7%94%A8%E4%BA%A7%E5%93%81%EF%BC%89%E6%89%B9%E5%8F%91%E9%9B%B6%E5%94%AE%E3%80%82%E3%80%90%E4%BE%9D%E6%B3%95%E9%A1%BB%E7%BB%8F%E6%89%B9%E5%87%86%E7%9A%84%E9%A1%B9%E7%9B%AE%EF%BC%8C%E7%BB%8F%E7%9B%B8%E5%85%B3%E9%83%A8%E9%97%A8%E6%89%B9%E5%87%86%E5%90%8E%E6%96%B9%E5%8F%AF%E5%BC%80%E5%B1%95%E7%BB%8F%E8%90%A5%E6%B4%BB%E5%8A%A8%E3%80%91%22,%22sbCompanyQualifications%22%3A%5B%7B%22id%22%3A%221441279471534333953%22,%22createUserId%22%3A%223%22,%22createUserName%22%3A%22%E4%B8%9A%E5%8A%A1%E7%AE%A1%E7%90%86%E5%91%98%22,%22organizationId%22%3A%221%22,%22createTime%22%3A%222021-09-24%2005%3A52%3A58%22,%22tenantId%22%3A%221%22,%22version%22%3A%221%22,%22validFlag%22%3A%221%22,%22deleteFlag%22%3A%220%22,%22updateUserId%22%3A%223%22,%22updateUserName%22%3A%22%E4%B8%9A%E5%8A%A1%E7%AE%A1%E7%90%86%E5%91%98%22,%22updateTime%22%3A%222021-09-24%2005%3A52%3A58%22,%22sbCompanyInfoId%22%3A%221441279471412699137%22,%22uaFileInfoId%22%3A%221441279342282539009%22,%22cqFileName%22%3A%22test.png%22,%22cqFileUrl%22%3A%22http%3A%2F%2F10.66.2.215%3A14048%2Fboss-v3%2Fresource%2Fimage%2Fpng%2F20210924055227518041156.png%22,%22cqFileType%22%3A%22image%2Fpng%22%7D%5D,%22eiType%22%3Anull,%22statusText%22%3A%22%E5%BE%85%E7%BC%96%E8%BE%91%22,%22PV_API_URL%22%3A%22%2Fus-upms%2Fsupplier%2FcompanyInfo%2FsaveAudit%22,%22ciCompanyTypeList%22%3A%5B%221%22%5D,%22ciAccountPeriod%22%3A%221%E5%B9%B4%22,%22isMicroEnt%22%3Anull,%22uuEnterpriseInfoId%22%3A%221441271925696225281%22,%22eiEstiblishTime%22%3Anull%7D&processInstanceId=9c6fee0c-1cfc-11ec-84d3-8677265336d4";
//       url = "http://192.168.20.114:8181/#/login";
//       url = "http://192.168.20.114:8181/#/app";
//         _title = "历史任务";

        break;
    }

    return url;
  }

  @override
  Widget build(BuildContext context) {
    print('url222:$url');

    return Scaffold(
        appBar: AppBar(
          title: Text(
            _title,
            style: TextStyle(color: YColors.r, fontSize: 18),
          ),
          backgroundColor: Colors.white,
          // 设置背景色
          leading: IconButton(
            icon: Image.asset(
              "images/return_back.png",
              width: 20,
              height: 20,
            ),
            onPressed: () {
//            Navigator.pop(context);
              /**
               *  获取是否可以依次关闭
               */
              Future canGoBack = _controller.canGoBack();
              canGoBack.then((str) {
                if (str) {
                  _controller.goBack();
                } else {
                  Navigator.of(context).pop();
                }
              });
            },
          ),
        ),
        body:
//        Column(
//          children: <Widget>[
//            RaisedButton(
//              child: Text("去设置缓存"),
//              onPressed: () {
//                setlocalStorage();
//              },
//            ),
//            RaisedButton(
//              child: Text("获取缓存了"),
//              onPressed: () {
//                _getCache();
//              },
//            ),
//            Container(
//////              height: TLSizeFit.screenHeight ,  //
//////              width: TLSizeFit.screenWidth,
//            color: YColors.bgH5,
//              child:
      Stack(
        children: <Widget>[
          SafeArea(
            child: WebView(
//          initialUrl: "https://flutterchina.club/",
//          initialUrl: "https://www.baidu.com/",
//          initialUrl: GlobalUrl.HELP,
//          initialUrl: _setWebviewUrl(),
              initialUrl: url,
//              initialUrl: '',
//                initialUrl: "file:assets/images/files/dist/index.html",
              //JS执行模式 是否允许JS执行

              onPageStarted: (String url) {
                print('onPageStarted 开始: $url');
//                setTitle();
//                  _getCache();
              },
              javascriptMode: JavascriptMode.unrestricted,
              onWebViewCreated: (WebViewController controller) {
                print("onWebViewCreated 创建");
                _controller = controller;
//                 _onAddToCache(controller, context);  // 自己添加的缓存的方法
                _controller.clearCache();  // 去掉缓存  防止标题重复

//                  setlocalStorage();
//                  _loadHtmlFromAssets();
              },

              onProgress: (int progress) {
                print("WebView is loading (progress : $progress%)");
                if(progress==100){
                  setState(() {
                    flagLoading = false;
                  });
                }

              },

              onPageFinished: (url) {
                print('onPageFinished: 完成');
//            _controller.evaluateJavascript("(function() { try { window.localStorage.setItem('userUuid', "
//                "'userUuid');window.localStorage.setItem('SZGDBoss3-token','authToken');); return window.localStorage.authToken; } "
//                "catch (err) { return err; } })();").then((result) {});

                setlocalStorage();
                _controller
                    .evaluateJavascript("document.title")
                    .then((result) {
                  print('onPageFinished。。。title:$result');
//                         _getCache();
                  if (result != "") {
                    setState(() {
                      _title = result;
                    });
                  }
                });
              },
              navigationDelegate: (NavigationRequest request) {
                print("即将打开 ${request.url}");
                if (request.url.startsWith("myapp://")) {
                  return NavigationDecision.prevent;
                }
                return NavigationDecision.navigate;
              },
              javascriptChannels: <JavascriptChannel>[
                JavascriptChannel(
                    name: "share",
                    onMessageReceived: (JavascriptMessage message) {
                      print("参数： ${message.message}");
                    }),
                //   https://www.jianshu.com/p/d9327b3c2b29 Flutter js 相互（调用）通信
//                https://www.jianshu.com/p/86916cab2cf3  Flutter 中 WebView 的使用以及与 JS 交互
                JavascriptChannel(
                    name: "messageBack",
                    onMessageReceived: (JavascriptMessage message) {
                      print("收到了方法，去返回");
//                      print("收到了方法，去返回:${message.message}");
//                      print(message.message);   // 我来自js调用sendMessage，我调用了Flutter中的功能
                      Navigator.of(context).pop("refresh");
//                        _controller?.evaluateJavascript("showMessage ('我（Flutter）收到了你的消息[${message.message}].)");

                    }),
              ].toSet(),
            ),
          ),
          flagLoading? LoadingDialog(text: "努力加载中"):Container(),

        ],
      ),

//            ),

//          ],
//        )
    );
  }

  /**
   * 后台返回的数据需要修改
   */
  setTitle()async{
    String title = await _controller.getTitle();
    print("获取的标题$title");
    setState(() {
//      _title = title;
    });
  }

  /**
   * https://www.jb51.net/article/174924.htm
   *
   */
  _loadHtmlFromAssets() async {
    print("加载本地");
    String fileHtmlContents = await rootBundle.loadString(filePath);
    print("fileHtmlContents:$fileHtmlContents");
    _controller.loadUrl(Uri.dataFromString(fileHtmlContents,
        mimeType: 'text/html', encoding: Encoding.getByName('utf-8'))
        .toString());
  }



  /*写入token到localStorage*/
//    原文链接：https://blog.csdn.net/Emperor_huanzi/article/details/109218249
  setlocalStorage() async{ //
    //

    // 需要修改 确认
//    String tokenKty = "SZGDBoss3__pre-token";  // 准生产
//    String tokenKty = "SZGDBoss3__dev-token";  // 开发
    String tokenKty = "SZGDBoss3__pro-token";  //  正式



    String access_token = await Storage.getToken(); //
    access_token = access_token.substring(7, access_token.length);
//    String access_token ="123333";
//    var loginData = await Storage.getString(Global.LOGINDATA);
//    print("设置缓存。。。access_token:$access_token");
    print("设置缓存。。。access_token:${access_token}");

    if (access_token != null) {
      print("设置缓存。。。3333");
//     _controller.evaluateJavascript("window.localStorage.setItem('SZGDBoss3-token','$access_token');");
//      _controller
//          .evaluateJavascript(
//              "window.localStorage.setItem('SZGDBoss3__pro-token','$access_token');")  // SZGDBoss3-token  $tokenKty  SZGDBoss3__pro-token
//          .then((res) => {
//                print("设置缓存成功了localStorage"),
//              });

//    原文链接：https://blog.csdn.net/win7583362/article/details/106408710
//       String script = "forFlutterInit('$access_token')";
//       _controller.evaluateJavascript(script).then((result) {
//         print("设置缓存成功了....:$result");
//         setState(() {
//           // ...
//         });
//       });


      var dictionary = await Storage.getString(Global.DICTIONARY);
      print("获取字典表....:$dictionary");
      if(dictionary!=null&&dictionary!=''){
        String scriptDictionary = "forFlutterDictionary('$dictionary')";
        _controller.evaluateJavascript(scriptDictionary).then((result) {
          print("设置缓存成功了.字典表成功...:$result");
        });
      }

      var loginInfor = await Storage.getString(Global.LOGINDATA);
      LogUtil.init(title: "来自LogUtil", isDebug: false, limitLength: 800);
      LogUtil.v("有缓存loginInfor:$loginInfor");
      // var logBean = json.decode(loginInfor); // Json 字符串转化成 Map 类型
      if(loginInfor!=null&&loginInfor!=''){
        String scriptDictionary = "forFlutterUserInfo('$loginInfor')";
        _controller.evaluateJavascript(scriptDictionary).then((result) {
          print("设置缓存成功了.用户信息...:$result");
        });
      }

//      _controller.evaluateJavascript(
//          "(function setData() { try { window.localStorage.setItem('SZGDBoss3-token', '$access_token');} catch (error) { return error; }})();");

//      print("设置缓存。。。2222");

//      _controller.evaluateJavascript("window.localStorage.setItem('userInfo','$loginData');");  // 用户信息

//      _controller.evaluateJavascript(
////        'caches.open("test_caches_entry"); localStorage["test_localStorage"] = "dummy_entry";');
////        'caches.open("token"); localStorage["token"] = "$access_token";');
//          'caches.open("SZGDBoss3-token"); localStorage["SZGDBoss3-token"] = "$access_token";');
//       setState(() {
//         print("重新赋值。。。");
//         url = url;
//       });


//      _controller.evaluateJavascript("(function() { try { window.localStorage.setItem('SZGDBoss3-token', '$access_token');window.localStorage.setItem('authToken','$authToken');); return window.localStorage.authToken; } catch (err) { return err; } })();").then((result) {});
//      _controller.evaluateJavascript("(function() { try { window.localStorage.setItem('SZGDBoss3-token', '${Global.ACCESS_TOKEN_VALUE}'); return window.localStorage.authToken; } catch (err) { return err; } })();").
//      then((result) {
//        print("设置缓存成功了result：");
//      });
    }
  }

  void _getCache(){  //async
    var getToken = _controller
        .evaluateJavascript("window.localStorage.getItem('SZGDBoss3-token')")
        .then((res) => {
          print("获取缓存getToken：$res"),
          if(res=="null"){
//              _controller.reload()  // 重新加载
//             print("再次去设置缓存2222。。。。。。："),
//             setlocalStorage(),
          }
        });

//    print("是否可以获取到缓存呢。。。getToken:$getToken");
//    String str = json.encode(getToken);
//    LogUtil.v("str:$str");
  }

  void _onAddToCache(WebViewController controller, BuildContext context) async {
    String access_token = await Storage.getToken();

    await controller.evaluateJavascript(
//        'caches.open("test_caches_entry"); localStorage["test_localStorage"] = "dummy_entry";');
//        'caches.open("token"); localStorage["token"] = "$access_token";');
        'caches.open("SZGDBoss3-token"); localStorage["SZGDBoss3-token"] = "$access_token";');
  }
}
